//
//  XWMainTabVC.swift
//  PersonalContacts
//
//  Created by xiewei on 16/12/1.
//  Copyright © 2016年 xiewei. All rights reserved.
//

import UIKit

class XWMainTabVC: UITableViewController {
    
    var personList = [XWPerson]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initDataOrOthers()
    }
    private func initDataOrOthers() -> () {
        tableView.rowHeight = 50
        loadData { (list) in
            print(list)
            
            self.personList += list
            self.tableView.reloadData()
        }
    }
    // MARK: - UITableViewDataSource
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return personList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let p = personList[indexPath.row];
        cell.textLabel?.text = p.name
        cell.detailTextLabel?.text = p.tel
        
        return cell
    }
    // MARK: - UITableViewDelegate
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        performSegue(withIdentifier: "vcSegue", sender: indexPath)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! XWDetailTabVC
        if let indexPath = sender as? IndexPath {
            vc.person = personList[indexPath.row]
            vc.completionCallBack = {
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
            }
        } else {
            // 很隐性的循环引用（vc对闭包进行强引用，闭包对vc进行强引用）
            vc.completionCallBack = {[weak vc] in
                guard let p = vc?.person else {
                    return
                }
                
                self.personList.insert(p, at: 0)
                self.tableView.reloadData()
            }
        }
    }
    
    @IBAction func addPerson(_ sender: UIBarButtonItem) {
        performSegue(withIdentifier: "vcSegue", sender: nil)
    }
    // 闭包默认的@no-escaping
    private func loadData(completion: @escaping (_ list: [XWPerson]) -> ()) -> () {
        DispatchQueue.global().async {
            Thread.sleep(forTimeInterval: 1)
            
            var arrM = [XWPerson]()
            for i in 0..<20 {
                let p = XWPerson()
                p.name = "xiewei--\(i)"
                p.tel = "1860" + String(format: "%06d", arc4random_uniform(1000000))
                arrM.append(p)
            }
            
            DispatchQueue.main.async {
                completion(arrM)
            }
        }
    }
}
